package com.china08.yxyapi.util;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * 云校微服务工具类 userId 是获得积分或减积分的人的Id
 * 
 * @author Json
 * 
 */
@Component
public class YxUserPointsUtilV3 {

    private final Logger LOGGER = LoggerFactory.getLogger(YxUserPointsUtilV3.class);

    // 微服务地址
    @Value("${yx.rest.service}")
    private String yxMsServer;

    @Value("${yx.rest.service.appid}")
    private String yxRestServiceAppid;

    @Value("${yx.rest.service.appsecret}")
    private String yxRestServiceAppsecret;

    @Autowired
    @Qualifier("templateForYxServer")
    private RestTemplate restTemplate;

    @Autowired
    @Qualifier("templateAsyncForYxServer")
    private AsyncRestTemplate asyncRestTemplate;

    /**
     * userId是要加积分人的Id
     */
    /**
     * 用户签到 返回值: -1 签到失败 0 已经敲到过 其他值 是本次签到所加的积分
     * 
     * @param userId
     * @return
     */
    public String signIn(String userId) {
        String code = "-1";
        String url = yxMsServer + "/rest/yxypoints/v3/%s/sign";
        url = String.format(url, userId);
        try {
            YxRsResponse response = restTemplate.getForObject(url, YxRsResponse.class);
            code = response.getMsg();
        } catch (Exception e) {
            code = "-1";
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 发送班级通知
     * 
     * @param userId
     */
    public void sendNotification(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/%s/notification";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 备授课-上课
     * 
     * @param userId
     */
    public void tackclass(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/backpack/%s/tackclass";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 备授课 创建备课包
     * 
     * @param userId
     */
    public void createBackpack(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/backpack/%s/create";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下架备课包
     * 
     * @param userId
     */
    public void downBackpack(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/backpack/%s/down";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 分享备课包
     * 
     * @param userId
     */
    public void shareBackpack(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/backpack/%s/share";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 备课包被采纳
     * 
     * @param userId
     */
    public void cainaBackpack(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/backpack/%s/caina";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 备授课发布作业
     * 
     * @param userId
     */
    public void homeworkBackpack(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/backpack/%s/homework";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送班级圈
     * 
     * @param userId
     */
    public void sendClassMessage(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/classmessage/%s/send";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除班级圈
     * 
     * @param userId
     */
    public void delClassMessage(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/classmessage/%s/delete";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 评论班级圈
     * 
     * @param userId
     */
    public void commentClassMessage(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/classmessage/%s/comment";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除班级圈评论
     * 
     * @param userId
     */
    public void delCommentClassMessage(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/classmessage/%s/comment/del";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 点赞班级圈
     * 
     * @param userId
     */
    public void praiseClassMessage(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/classmessage/%s/praise";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发布妙招
     * 
     * @param userId
     */
    public void discoverMiaozhao(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/discover/%s/miaozhao";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发现-发布评论
     * 
     * @param userId
     */
    public void discoverComment(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/discover/%s/comment";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发现-点赞
     * 
     * @param userId
     */
    public void discoverPraise(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/discover/%s/praise";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发现获得赞
     * 
     * @param userId
     */
    public void discoverPraiseGet(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/discover/%s/get/praise";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送作业
     * 
     * @param userId
     */
    public void sendHomework(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/homework/%s/send";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 学生提交作业<=50%
     * 
     * @param userId
     */
    public void finishHomework50(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/homework/%s/finish/less";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 学生提交作业>=50% <=80%
     * 
     * @param userId
     */
    public void finishHomeworkOther(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/homework/%s/finish/other";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 学生提交作业>=80%
     * 
     * @param userId
     */
    public void finishHomeworkMore(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/homework/%s/finish/more";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 老师批阅主观题
     * 
     * @param userId
     */
    public void readHomework(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/homework/%s/read";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传视频
     * 
     * @param userId
     */
    public void uploadResourceVideo(String userId) {

        String url = yxMsServer + "/rest/yxypoints/v3/resource/%s/video";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文档
     * 
     * @param userId
     */
    public void uploadResourceTxt(String userId) {

        String url = yxMsServer + "/rest/yxypoints/v3/resource/%s/txt";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 分享资源
     * 
     * @param userId
     */
    public void shareResource(String userId) {

        String url = yxMsServer + "/rest/yxypoints/v3/resource/%s/share";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下架视频
     * 
     * @param userId
     */
    public void downResourceVideo(String userId) {

        String url = yxMsServer + "/rest/yxypoints/v3/resource/%s/down/video";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下架文档
     * 
     * @param userId
     */
    public void downResourceTxt(String userId) {

        String url = yxMsServer + "/rest/yxypoints/v3/resource/%s/down/txt";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建考试
     * 
     * @param userId
     */
    public void createExam(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/exam/%s/create";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传成绩
     * 
     * @param userId
     */
    public void uploadScore(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/exam/%s/score";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送报告
     * 
     * @param userId
     */
    public void sendReport(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/exam/%s/report";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除考试
     * 
     * @param userId
     */
    public void examDel(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/exam/%s/del";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 撤回报告
     * 
     * @param userId
     */
    public void delReport(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/exam/%s/del/report";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除创建
     * 
     * @param userId
     */
    public void delCreate(String userId) {
        String url = yxMsServer + "/rest/yxypoints/v3/exam/%s/del/create";
        url = String.format(url, userId);
        try {
            executeAsyncRequest(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 异步调用方法
    private void executeAsyncRequest(String url) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        String token = Base64Utils
                .encodeToString((yxRestServiceAppid + ":" + yxRestServiceAppsecret).getBytes("UTF-8"));
        headers.add("Authorization", "Basic " + token);
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        HttpEntity<Object> request = new HttpEntity<Object>(null, headers);

        ListenableFuture<ResponseEntity<YxRsResponse>> postForEntity = asyncRestTemplate.postForEntity(url, request,
                YxRsResponse.class);
        postForEntity.addCallback(new ListenableFutureCallback<ResponseEntity<YxRsResponse>>() {
            @Override
            public void onSuccess(ResponseEntity<YxRsResponse> result) {
                LOGGER.info("请求成功:" + result.getBody().getMsg());

                if ("0".equals(result.getBody().getMsg())) {
                    LOGGER.info("请求成功:本次没有加积分,积分已到上限");
                } else if ("-1".equals(result.getBody().getMsg())) {
                    LOGGER.info("请求成功:本次没有加积分,加积分异常");
                } else {
                    LOGGER.info("请求成功,积分已加");
                }
            }

            @Override
            public void onFailure(Throwable t) {
                LOGGER.error("请求异常:" + t.getMessage());
            }
        });
    }

}

@JsonIgnoreProperties(ignoreUnknown = true)
class YxRsResponse implements Serializable {
    private static final long serialVersionUID = -1877626679846741238L;
    // 0 正常 1 异常
    private String event;
    private String msg;

    public boolean getEvent() {
        return "1".equals(this.event) ? false : true;
    }

    public void setEvent(String event) {
        this.event = event;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
